// rechange.js 2017-12-12
 function gohref() {//跳转问题反馈
    window.open("/recharge/question.html");    
}
$(function () {
    var djsshowprice, djstimes,begindjs, reqstime, reqetime, reqcha, serviceTime, thistime, gethours, getMinutes, getSecond, intervalL, timeinterval, timetimeout;
    function timeShow() {
        djsshowprice = true;
        function setproducttime() {
            djstimes = serviceTime.getTime();//当前时间
            var ndate = serviceTime;
            var year = ndate.getFullYear();
            var month = ndate.getMonth() + 1;
            var date = ndate.getDate();
            var off = true
            if (ndate.getHours() == '00' && off) {//
                var pretime = new Date(serviceTime.getTime() - 86400000)
                date = pretime.getDate();
                month = pretime.getMonth() + 1;
                off = false;
            }
            // 通过返回的时间段生成结束时间
            var newDate = year + '-' + month + '-' + date + ' ' + gethours + ':' + getMinutes + ':' + getSecond;
            newDate = new Date(newDate.replace(/-/g, '/')).getTime();//设定时间
            var enddjs = thistime * 60000 + 1000;//时间段
            var cdate = newDate + enddjs//结束时间
            // console.log(new Date(cdate))
            function djsminutes() {
                djsshowprice = false;
                djsmin = parseInt(enddjs / 60000);
                djssec = parseInt(enddjs % 60000 / 1000);
                if (djssec && djsmin) {
                    begindjs = djsmin + '分' + djssec + '秒';
                } else if (!djssec && djsmin) {
                    begindjs = djsmin + '分';
                } else if (!djsmin) {
                    begindjs = djssec + '秒';
                }
                $('#subChangegray').html(begindjs);
            }
            if (djstimes >= newDate && djstimes <= cdate) {
                thisdjs = djstimes - newDate;
                enddjs = enddjs - thisdjs;
                djsminutes()
                $('#subChange').hide();
                $('#graybtnwrap').show();
                clearInterval(timeinterval)
                timeinterval = setInterval(function () {
                    if(!(window.location.pathname=="/index.html"||window.location.pathname=="/recharge/index.html")){
                        clearInterval(timeinterval)
                    }
                    if (djstimes >= cdate) {
                        djsshowprice = true;
                        $('#subChange').show();
                        $('#graybtnwrap').hide();
                        clearInterval(timeinterval)
                    } else {
                        enddjs = enddjs - 1000;
                        djsminutes();
                    }
                }, 1000)
            }else{
               $('#subChange').show(); 
            }
            clearTimeout(timetimeout)
            timetimeout = setTimeout(function () {
                serviceTime = new Date(serviceTime.getTime() + 1000);
            }, 300);
        }
        setproducttime();
        clearInterval(intervalL)
        intervalL =setInterval(function () {
            setproducttime()
            if(!(window.location.pathname=="/index.html"||window.location.pathname=="/recharge/index.html")){
                clearInterval(intervalL)
            }
        }, 1000)
    }
    // 获取请求开始的时间
    reqstime = new Date().getTime();
    $.get(ajaxURL + "/api/UserFlexibleProduct/GetServiceTime", {}, function (result) {
        // 获取请求结束的时间
        reqetime = new Date().getTime();
        // 计算请求所用时间
        reqcha = reqetime - reqstime;
         // 后台返回的时间加上请求所用时间就是当前时间
         serviceTime = new Date(new Date(parseInt(result.data.serviceTime)).getTime() + reqcha);//
         //时间段
         thistime = result.data.minute;
         //开始时间
         gethours = result.data.startTime.substring(0, 2);
         getMinutes = parseInt(result.data.startTime.substring(3, 5));
         getSecond = parseInt(result.data.startTime.substring(6, 8));
         timeShow();
    })
    var uid = localStorage.getItem('uid');//登陆uid
    var fullName = "",
        bankCode = "",
        usrCustId = "";

    function initdata(){
        var rechangeName = $('#rechangeName');//姓名
        var rechangeTel = $('#rechangeTel');//手机号
        var myprice = $('#myprice');//剩余金额
        var rechangePrice = $('#rechangePrice');//充值后可用余额
        $.ajax({//用户姓名 手机号 是否实名
            url: ajaxURL + '/api/user/getuserinfo',
            type: 'POST',
            async: false,
            data: {
                u_id: uid
            },
            timeout: 5000,
            dataType: 'json',
            contentType: "application/x-www-form-urlencoded",
            success: function (data) {
                if (data.code == 1) {
                    layer.closeAll();
                    fullName=data.data.fullName
                    bankCode=data.data.bankCode
                    usrCustId=data.data.usrCustId
                    if(data.data.fullName){
                        rechangeName.text(data.data.fullName)
                        rechangeTel.text(data.data.userName)
                    }else{
                        rechangeName.text('未实名')
                        rechangeTel.text('尚未进行实名认证')
                    }
                } else if (data.code == 8) {
                    location.pathname = '/recharge/login.html'
                } else {
                    layer.msg(data.data);
                }
            },
            error: function (err) {
                layer.msg('接口错误');
            }
        })
        $.ajax({//用户剩余金额 充值后金额
            url: ajaxURL + '/api/price/myprice',
            type: 'POST',
            async: true,
            data: {
                u_id: uid
            },
            timeout: 5000,
            dataType: 'json',
            contentType: "application/x-www-form-urlencoded",
            success: function (data) {
                if (data.code == 1) {
                    layer.closeAll();
                    data.data.usableAmount=data.data.usableAmount?data.data.usableAmount:'0';
                    myprice.text(data.data.usableAmount);
                    rechangePrice.text(data.data.usableAmount);
                } else if (data.code == 8) {
                    location.pathname = '/recharge/login.html'
                } else {
                    layer.msg(data.data);
                }
            },
            error: function (err) {
                layer.msg('接口错误');
            }
        })
    }
    initdata()
    var redMessage=$('.red_message');
    $('.close_bth span').click(function(){
         layer.closeAll();
    })
    $('.but_bg').click(function(){
        layer.closeAll();
    })
    $('#rechargeInput').keyup(function(e){//键入清除提示文字
        redMessage.text('');    
        var price =  $('#rechargeInput').val();
        price = price.replace(/[^\d.]/g, "");
        //必须保证第一个为数字而不是. 
        price = price.replace(/^\./g, "");
        //保证只有出现一个.而没有多个. 
        price = price.replace(/\.{2,}/g, ".");
        //保证.只出现一次，而不能出现两次以上 
        price = price.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
        if (price.indexOf(".") > -1) {
            price = price.substring(0, price.indexOf(".") + 3);
        }
        if(price > 50000000){
            price = 50000000
        }
        $('#rechargeInput').val(price);
        var accmyprice=accAdd($('#myprice').text(),$('#rechargeInput').val())
        $('#rechangePrice').text(accmyprice)
        
    })
    $('#subChange').click(function () {//提交充值
        if(!usrCustId){
            layer.open({
                type: 1,
                area: ['857px', '722px'], //宽高
                title:'<span>提示</span>',
                content: $('#fmbankcg')
            })
            return false
        }
        // else if(!bankCode){
        //     layer.open({
        //         type: 1,
        //         area: ['857px', '722px'], //宽高
        //         title:'<span>提示</span>',
        //         content: $('#nobankcg')
        //     })
        //     return false
        // }
        var rechargeInput = $('#rechargeInput').val()
        rechargeInput = Number(rechargeInput).toFixed(2)
        if (rechargeInput <= 0||rechargeInput > 50000000||!$('#rechargeInput').val()) {
            redMessage.text('请输入有效的充值金额')
            return false
        }
        $.ajax({//
            url: ajaxURL + '/api/Account/DepositApply',
            type: 'POST',
            async: false,
            data: {
                RetUrl: '',
                // OpenBankId: 'CIB', //测试只限光大银行
                OpenBankId: bankCode,
                PageType: '',
                GateBusiId: "B2C",
                TransAmt: rechargeInput,
                u_id: uid
            },
            timeout: 5000,
            dataType: 'json',
            contentType: "application/x-www-form-urlencoded",
            success: function (result) {
                if(result.code==2){
                    layer.msg(result.data);
                }else{
                    redMessage.text('');
                    layer.closeAll();
                    var myform = $('<form></form>')
                    myform.attr('action', hfUrl);  
                    myform.attr('method', 'post');
                    myform.attr('target', '_blank');
                    // result.usrCustId = "6000060008282478";
                    for(var i in result){//动态变异form
                        res = i.substring(0,1).toUpperCase()+i.substring(1);//处理name值首字母大写
                        if(result[i]==null){//参数值为null处理为空字符串
                            result[i]="";
                        }
                        var html = '<input type="hidden" name="'+res+'" id="'+res+'" value="'+result[i]+'"/>'
                        var my_input = $(html); 
                        myform.append(my_input);
                    }
                    setTimeout(function () {
                        console.log(myform[0])
                        myform.appendTo('body').submit();
                    }, 50)
                    // $('#merchant_id').val(data.data.result.merchantId)//form提交表单
                    // $('#merchant_data').val(data.data.result.data)
                    // $('#encryptkey').val(data.data.result.encrypKey)
                    // $('#myform')[0].action = data.data.url;
                    // var formObject = document.querySelector('form')
                    // $('#myform').submit();
                    layer.open({
                        type: 1,
                        area: ['857px', '722px'], //宽高
                        title:'<span>提示</span>',
                        content: $('#hideindex'),
                        end:function(){
                            initdata()
                        }
                    })
                    $('#rechargeInput').val("")
                }
                
            },
            error: function (err) {
                layer.msg('接口错误');
            }
        })
    })
})